<?php
/**
 * 腾讯登录接口
 */
class LoginMsdk extends APIBase {

	public $tag = "LoginMsdk";
	public $isLogin = false;

	public function before() {
		$this->initMysql();
		$this->initCacheRedis();
		$this->inithttp();
		return true;
	}

	public function logic() {
        //error_reporting(0);
        //
		$ip = $this->getRealIp();
		$vercode= '';
		$ua = '';
	    $imsi = '';
		$imei = '';
		$cid = '';
		$channel = '000550';
		
		//user_sdk channel skey user_id 
		//file_put_contents('1.txt',"01\n",FILE_APPEND);
		if (!isset($this->param['open_id'])&& $this->param['open_id']=='') {
			$this->returnError(311,"登录错误！");	
			
		}else{
			$open_id = $this->param['open_id'];
			//file_put_contents('1.txt',"1\n",FILE_APPEND);
		}
		
		if (!isset($this->param['open_key'])&& $this->param['open_key']=='') {
			$this->returnError(311,"登录错误！");	
			
		}else{
			$open_key = $this->param['open_key'];
			//file_put_contents('1.txt',"1\n",FILE_APPEND);
		}
        

		if ( !isset($this->param['puid'])&& $this->param['puid']=='' ){
			$this->returnError(315,"登录错误！");
		}else{
			$puid = $this->param['puid'];
		}
		
		if ( !isset($this->param['platform'])&& $this->param['platform']=='' ){
			$this->returnError(316,"登录错误！");
		}else{
			$platform = $this->param['platform'];
		}
		//file_put_contents('1.txt',"6\n",FILE_APPEND);
        //
		//qq登录验证
		if((int)$this->param['platform']==2){
			
			$data = array(
			   'appid'=>Config::$appid,
			   'openid'=>$this->param['open_id'],
			   'openkey'=>$this->param['open_key'],
			   'userip'=>$ip
			);
			$timestamp = time();
			Config::$logger->info($this->tag,"data:".json_encode($data));
		    Config::$logger->info($this->tag,"appkey:".Config::$appkey);
			$sig = md5(Config::$appkey.$timestamp);
			
			Config::$logger->info($this->tag,"sig:".$sig);
			$yzresult = $this->http->Postjson('http://msdk.qq.com/auth/verify_login/?timestamp='.$timestamp.'&appid='.Config::$appid.'&sig='.$sig.'&openid='.$this->param['open_id'].'&encode=1',$data);
			Config::$logger->info($this->tag,"qq:".$yzresult);
			$yzresult = json_decode($yzresult,true);
			if($yzresult['ret']!=0){
				
				$this->returnError(122,"登录错误！");
			}
		//微信登录验证	
		}elseif((int)$this->param['platform']==1){
		    $data = array(
		
			   'openid'=>$this->param['open_id'],
			   'accessToken'=>$this->param['open_key'],
		
			);
			
			$timestamp = time();
			Config::$logger->info($this->tag,"data:".json_encode($data));
		   // Config::$logger->info($this->tag,"appkey:".Config::$appkey);
			$sig = md5(Config::$wxappkey.$timestamp);
			
			Config::$logger->info($this->tag,"sig:".$sig);
			$yzresult = $this->http->Postjson('http://msdk.qq.com/auth/check_token/?timestamp='.$timestamp.'&appid='.Config::$wxappid.'&sig='.$sig.'&openid='.$this->param['open_id'].'&encode=1',$data);
			Config::$logger->info($this->tag,"wx:".$yzresult);
			$yzresult = json_decode($yzresult,true);
			if($yzresult['ret']!=0){
				
				$this->returnError(122,"登录错误！");
			}
			
		
		}else{
			$this->returnError(311,"登录错误！");	
		}
		
		
		
		
		
		$user = (string)$channel . (string)$open_id;
		//file_put_contents('./data3.txt',json_encode($_SESSION), FILE_APPEND);
		//exit;
		//unset($_SESSION[$user]);
		//账号
		 
	     $row = $this->mysql->select("player", "*", array('user' => $user));
		 $c = count($row);
		 
			if ($c == 0)
			{
				//查找puid不存在，新手机用户
				//自动注册
				
				$where_ip = array('register_ip' => trim($ip));
				$ipdata = $this->mysql->select("player", "COUNT(*) AS `count`", $where_ip);
			
				//if ($ipdata[0]['count'] > Game::$limit_user) {
				if ($ipdata[0]['count'] > 10) {	
					$this->returnError(513, '该设备已经超出可注册用户范围！');
				}
				
				$where_puid = array('puid' => trim($puid));
				$puiddata = $this->mysql->select("player", "COUNT(*) AS `count`", $where_puid);
			
				//if ($ipdata[0]['count'] > Game::$limit_user) {
				if ($puiddata[0]['count'] > 10) {	
					$this->returnError(513, '该设备已经超出可注册用户范围！');
				}
				
				
				while(1){
				  $user_name = 'TX'.rand(1, 100000);
				  $row = $this->mysql->select("player", "*", array('name' => $user_name));
				  if(count($row)==0){
					  break;
				  }
				}
				
			
				
				
				
				$user_info = $this->AutoReg($puid,$platform,$vercode,$ua,$imsi,$imei,$cid,$channel,$open_id,$ip,$user_name);
				//Config::$logger->info($this->tag.'--', json_encode($user_info));
				$this->returnData($user_info);
			}
			elseif ($c > 1)
			{
				$this->e("{$puid} repeat");
				$this->returnError(500, "server error.");
			}
			else 
			{
				//puid已经存在,则用puid直接登陆
				if ($row[0]['status'] == 0) 
				{
					$this->returnError(310,"账号异常，请联系客服！");
				}
				$uid = $row[0]['id'];
				$this->initDataRedis($uid);
			
				$isExists = $this->data_redis->exists("hu:{$uid}");
				$player = $this->data_redis->hMGet("hu:{$uid}", array('id','user'));
				if (!$isExists || $player['id']==null || $player['user'] == null) {
					$this->data_redis->hMset("hu:{$uid}", $row[0]);
				}
			
				$this->continuous_landing($uid);
				
				$salt = $this->data_redis->hGet("hu:{$uid}", 'salt');
				$now = time();
				$skey = md5($now . $salt);
				//
				$oldip = $this->data_redis->hGet("hu:{$uid}",'login_ip');
				
				$this->data_redis->hMset("hu:$uid", array("update_time" => $now, "heartbeat_at" => $now, "skey" => $skey,"login_ip"=>$ip));
				$this->mysql->update("player", array('update_time'=>$now), array('id' => $uid ));
				//$vercodes = (int)$this->param['vercode'];
				//$this->data_redis->hSet("hu:$uid", "vercode", $vercodes);
			
				$user_info = $this->data_redis->hMget("hu:$uid", array(
					'user', 'name', 'sex', 'money', 'coin', 'skey','salt',
					'login_days', 'is_get', 'total_board', 'total_win', 'exp',
					'bank', 'password', 'is_set_bank_password','avater_url',
					'gift_num1','gift_num2','gift_num3','gift_num4','charisma','activity',
					'isget_coin_task_reward_record','coin_task_complete_record',
                    'changeCardtoolNum','betsDoubletoolNum','banComparetoolNum','channel','is_vip','vip_time','signature','avater_url','bindpuid',''
				));
				
				//剩余天数
				//$user_info['remaining'] = 0;
			   if((int)$user_info['is_vip']&& time()<(int)$user_info['vip_time']){
			  
			     $remaining = ceil(((int)$user_info['vip_time']-time())/86400);
			     $user_info['remaining'] = $remaining;
			  	 Config::$logger->info($this->tag, 'remaining'.$remaining);
			 //会员登录通知
			     $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=Marquee&receiver=all&param={"user":"'.$user_info['name'].'","type":1}';
			   if(!$this->http->get($url)){
				   // $this->returnError(599, "通知异常！");
			   }
			    
			   }else{
			 //
			 /* $this->data_redis->hMset("hu:$uid",array('is_vip'=>0)); 	*/
			      $user_info['remaining'] = 0; 	
				   $user_info['is_vip'] = 0;			
			   }
				

				$user_info['password'] = (string)$user_info['salt']; //登陆密码
				$user_info['uid'] = (int)$uid;
				$user_info['sex'] = (int)$user_info['sex'];
				$user_info['money'] = (int)$user_info['money'];
				$user_info['coin'] = (int)$user_info['coin'];
				$user_info['login_days'] = (int)$user_info['login_days'];
				$user_info['is_get'] = (int)$user_info['is_get'];
				$total_lose = $user_info['total_board'] - $user_info['total_win'];
				$user_info['history'] = array((int)$user_info['total_win'], (int)$total_lose);
				$user_info['total_board'] = (int)$user_info['total_board'];
				$user_info['total_win'] = (int)$user_info['total_win'];
				$user_info['exp'] = (int)$user_info['exp'];
				$user_info['is_vip'] = (int)$user_info['is_vip']?(int)$user_info['is_vip']:0;
				$user_info['bank'] = (int)$user_info['bank'];
				$user_info['is_set_bank_password'] = (int)$user_info['is_set_bank_password'];
				$user_info['password'] = $user_info['password'];
				$user_info['gift_num1'] = (int)$user_info['gift_num1'];
				$user_info['gift_num2'] = (int)$user_info['gift_num2'];
				$user_info['gift_num3'] = (int)$user_info['gift_num3'];
				$user_info['gift_num4'] = (int)$user_info['gift_num4'];
				$user_info['charisma'] = (int)$user_info['charisma'];
				$user_info['activity'] = (int)$user_info['activity'];
				$user_info['isget_coin_task_reward_record'] = (int)$user_info['isget_coin_task_reward_record'];//是否领取奖券任务奖励记录
				$user_info['changeCardtoolNum'] = (int)$user_info['changeCardtoolNum'];
                $user_info['betsDoubletoolNum'] = (int)$user_info['betsDoubletoolNum'];
                $user_info['banComparetoolNum'] = (int)$user_info['banComparetoolNum'];
				$user_info['channel'] = (string)$user_info['channel'];
				$user_info['signature'] =  $user_info['signature']?$user_info['signature']:'';
			    $user_info['avater_url'] = (int)$user_info['avater_url']?(int)$user_info['avater_url']:1;
				
				$user_info['bindpuid'] = $user_info['bindpuid']?'true':'false';
				
				if($oldip !=''){
				  	
				  if($oldip != $ip){
					  
					$user_info['last_ip'] = $oldip;
					  
				  }else{
					
					$user_info['last_ip'] = '';
					   
				  }
				}else
				{
				   $user_info['last_ip'] = '';
				}
				
                $user_info['ip'] = Config::$ip_server_confing['ip'];
			    $user_info['port'] = Config::$ip_server_confing['port'];
				
				$vga = $this->cache_redis->hGetall("vga");
				$user_info['upvenus'] = $vga['upvenus'];
				$user_info['upgoods'] = $vga['upgoods'];
				//Config::$logger->info($this->tag.'--', json_encode($user_info));
				//file_put_contents('auto.txt',json_encode($user_info));
				$this->returnData($user_info);
			}
						
		
	}
		
	private function AutoReg($puid,$platform,$vercode,$ua,$imsi,$imei,$cid,$channel,$open_id,$ip,$user_name)
	{
		
		$users = (string)$channel.(string)$open_id;
		$password = rand(1, 1000000);
		$new_user = $this->createUser($users,$password,$puid,$platform,$vercode,$ua,$imsi,$imei,$cid,$channel,$ip,$user_name);
			
		$uid = $this->mysql->insert("player", $new_user);
		if ($uid == 0) {
			$this->e("insert user error");
			$this->returnError(500, "server is error");
		}
		
		//记录注册赠送金币
		$m_rec['type'] = 7;
		$m_rec['uid'] =$uid;
		$m_rec['money'] = Game::$init_money;
		$m_rec['change_money'] = Game::$init_money;
		$this->addChangeMongeyLog($m_rec);
		
		$this->initDataRedis($uid);
		$new_user['id'] = $uid;
		$ret = $this->data_redis->hMset("hu:{$uid}", $new_user);
		if (!$ret) {
			$this->e("redis hMset error.");
			$this->returnError(3, "redis hMset error.");
		}
			
		$title = "欢迎您来到" . Game::$appname;
		$content = "欢迎您来到" . Game::$appname . "首次登陆赠送" . Game::$init_money . "金币，连续每日登陆，还能获得更多免费金币，首次充值也会赠首充礼包哦！";
		//$this->sendMessage($uid, $title, $content);
			
		$user_info = $this->data_redis->hMget("hu:$uid", array(
			'user', 'name', 'sex', 'money', 'coin', 'skey',
			'login_days', 'is_get', 'total_board', 'total_win', 'exp',
			'bank', 'bank_password', 'is_set_bank_password','avater_url',
			'gift_num1','gift_num2','gift_num3','gift_num4','charisma','activity',
			'isget_coin_task_reward_record','coin_task_complete_record',
            'changeCardtoolNum','betsDoubletoolNum','banComparetoolNum','is_vip','signature','avater_url','bindpuid'
		));
		$user_info['password'] = (string)$password; //登陆密码
		$user_info['uid'] = (int)$uid;//用户ID
		$user_info['sex'] = (int)$user_info['sex'];//性别
		$user_info['money'] = (int)$user_info['money'];//游戏币
		$user_info['coin'] = (int)$user_info['coin'];//元宝
		$user_info['login_days'] = (int)$user_info['login_days'];//连续登陆天数
		$user_info['is_get'] = (int)$user_info['is_get'];//是否领取了当天的连续登陆奖励
		$total_lose = $user_info['total_board'] - $user_info['total_win'];
		$user_info['history'] = array((int)$user_info['total_win'], (int)$total_lose);//输赢局数
		$user_info['total_board'] = (int)$user_info['total_board'];//总局数
		$user_info['total_win'] = (int)$user_info['total_win'];//总赢局数
		$user_info['bank'] = (int)$user_info['bank'];//保险箱存款
		$user_info['is_set_bank_password'] = (int)$user_info['is_set_bank_password'];
		$user_info['exp'] = (int)$user_info['exp'];//经验值
		$user_info['is_vip'] = 0;
		//$user_info['vip_time'] = (int)$user_info['vip_time']?(int)$user_info['vip_time']:0;
		
		$user_info['gift_num1'] = (int)$user_info['gift_num1'];
		$user_info['gift_num2'] = (int)$user_info['gift_num2'];
		$user_info['gift_num3'] = (int)$user_info['gift_num3'];
		$user_info['gift_num4'] = (int)$user_info['gift_num4'];
		$user_info['charisma'] = (int)$user_info['charisma'];
		$user_info['activity'] = (int)$user_info['activity'];
		$user_info["isget_coin_task_reward_record"] = (int)$user_info['isget_coin_task_reward_record'];//是否领取奖券任务奖励记录
        $user_info['changeCardtoolNum'] = (int)$user_info['changeCardtoolNum'];
        $user_info['betsDoubletoolNum'] = (int)$user_info['betsDoubletoolNum'];
        $user_info['banComparetoolNum'] = (int)$user_info['banComparetoolNum'];
		$user_info['signature'] =  $user_info['signature']?$user_info['signature']:'';
		$user_info['avater_url'] = (int)$user_info['avater_url']?(int)$user_info['avater_url']:1;
		$user_info['ip'] = Config::$ip_server_confing['ip'];
	    $user_info['port'] = Config::$ip_server_confing['port'];
		$user_info['remaining'] = 0;
		$user_info['bindpuid'] = $user_info['bindpuid']?'true':'false';
		$user_info['last_ip'] = '';
		
		
        $vga = $this->cache_redis->hGetall("vga");//服务器数据更改时间戳
		$user_info['upvenus'] = $vga['upvenus'];
		$user_info['upgoods'] = $vga['upgoods'];

		//file_put_contents('u.txt',json_encode($user_info));  
		return $user_info;
	}
			

	private function createUser($user,$password,$puid,$platform,$vercode,$ua,$imsi,$imei,$cid,$channel,$ip,$user_name) {
		$now = time();
		$user_auto = $user;
		$password_auto = $password;
		$bank_password_auto = '123456';	
		$user_info = array();
		$user_info["user"] = $user_auto;
		
		if ($user_name != " " && $user_name != "")
		{
			//if(strlen($ua) > 9) $_ua = substr($ua,0,9);
			//else $_ua = $ua;
			$user_info["name"] = $user_name;
		}
		else
		{
			$user_info["name"] = $user_auto;
		}
		$user_info["password"] = md5($password_auto . $password_auto);
		$user_info["salt"] = $password_auto;
		$user_info["status"] = 1; // 0：为封号的
		$user_info["puid"] = $puid;
		$user_info["platform_type"]=$platform;
		$user_info["sex"] = rand(1,2);
		$user_info["money"] = Game::$init_money;
		$user_info["coin"] = Game::$init_coin;
		$user_info["skey"] = md5(time().$password_auto);
		$user_info["login_days"] = 0;
		$user_info["is_get"] = 0;
		$user_info["total_board"] = 0;
		$user_info["total_win"] = 0;
		$user_info["vercode"] = $vercode;
		$user_info["ua"] = $ua;
		$user_info["imsi"] = $imsi;
		$user_info["imei"] = $imei;
		$user_info["cid"] = $cid;
		$user_info["channel"] = $channel;
		$user_info["exp"] = 0;
		$user_info["heartbeat_at"] = $now;
		$user_info["broke_num"] = 0;
		$user_info["broke_time"] = 0;
		$user_info["create_time"] = $now;
		$user_info["update_time"] = $now;
		$user_info["bank"] = 0;
		$user_info["bank_password"] = md5($bank_password_auto . $bank_password_auto);
		$user_info["bank_salt"] = $bank_password_auto;
		$user_info["is_set_bank_password"] = 1;
		$user_info["avater_url"] = "";
		$user_info["gift_num1"] = 0; //礼物1 鸡蛋
		$user_info["gift_num2"] = 0; //礼物2 鲜花
		$user_info["gift_num3"] = 0; //礼物3 汽车
		$user_info["gift_num4"] = 0; //礼物4 游艇
		$user_info["charisma"] = 0;  //魅力属性值
		$user_info["activity"] = 0; //活跃度属性
		$user_info["isget_coin_task_reward_record"] = 0;//是否领取奖券任务奖励记录
		$user_info["coin_task_complete_record"] = "0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0";
        $user_info["changeCardtoolNum"] = 2;
        $user_info["betsDoubletoolNum"] = 2;
        $user_info["banComparetoolNum"] = 2;
		$user_info["is_visitor"] = 1;
		$user_info["is_vip"] = 0;
		$user_info["vip_time"] = 0;
		$user_info["register_ip"] = $ip;
		$user_info["login_ip"] = $ip;
		$user_info['signature'] = '';
		$user_info['avater_url'] = 1;
		$user_info['bindpuid'] = '';
		//$user_info['last_id'] = '';
		//file_put_contents('auto.txt',json_encode($user_info));
		return $user_info;
	}
	
	/**
	 * 连续登录
	 */
	private function continuous_landing($uid) {
		$ts = strtotime(date("Y-m-d"));
		$update_time = $this->data_redis->hGet("hu:{$uid}", 'update_time');
		$login_days = $this->data_redis->hGet("hu:{$uid}", 'login_days');
		
		if ($update_time <= $ts) {
			$this->data_redis->hset("hu:{$uid}", "lottery_count", 0); //lottery times
			if ($update_time > ($ts - 86400)) {
				//$this->data_redis->hincrBy("hu:{$uid}", "login_days", 1);
				$this->data_redis->hset("hu:{$uid}", "is_get", 0);
				if((int)$login_days==7){
						 $this->data_redis->hset("hu:{$uid}", "login_days", 0);
					}
			} else {
				$this->data_redis->hMset("hu:{$uid}", array("login_days" => 0, "is_get" => 0));
			}
		}
	}
    
    	
	 
	 
	public function after() {
		$this->deinitDataRedis();
		$this->deinitCacheRedis();
		$this->deinitMysql();
		$this->deinithttp();
	}
}
?>
